package com.xbongbong.workflow.service.help.saas;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PaymentSheetTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.SerialNoHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.AddMuchFieldPojo;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataDeleteBatchDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.service.WorkflowOperatorDataService;
import com.xbongbong.paas.service.workflow.WorkflowDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.PackageStatusEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.payment.pojo.dto.PaymentDTO;
import com.xbongbong.pro.paymentsheet.pojo.dto.batch.PaymentSheetDTO;
import com.xbongbong.pro.paymentsheet.pojo.vo.batch.PaymentSheetAmountVO;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.help.FundHelp;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.FundSetModel;
import com.xbongbong.saas.service.PaymentService;
import com.xbongbong.saas.service.toolbox.help.PackageStatusHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;

/**
 *
 * @author 魏荣杰
 *
 */
@Component
@Slf4j
public class ContractForPaymentHelp {

    @Resource
    private PackageStatusHelp packageStatusHelp;
    @Resource
    private PaymentService paymentService;
    @Resource
    private ContractModel contractModel;
    @Resource
    private UserModel userModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private SerialNoHelp serialNoHelp;
    @Resource
    private FundSetModel fundSetModel;
    @Resource
    private WorkflowOperatorDataService workflowOperatorDataService;
    @Resource
    private WorkflowDataService workflowDataService;

    /**
     * Description: 保存回款计划（应收款）
     * @param workflowTransferPOJO
	 * @param saasNeedRedundantAttrPojo
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2021/8/17 14:31
     * @since
     */
    public void savePayment(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        if (Objects.nonNull(saasNeedRedundantAttrPojo) && Objects.nonNull(saasNeedRedundantAttrPojo.getAddBatchDTO())) {
            String corpid = workflowTransferPOJO.getCorpid();
            Integer isImport = workflowTransferPOJO.getIsImport();
            Data pojoData = workflowTransferPOJO.getData();
            Long contractId = pojoData.getId();
            JSONObject data = pojoData.getData();
            User user = workflowTransferPOJO.getUser();

            List<AddMuchFieldPojo> addBatchList = saasNeedRedundantAttrPojo.getAddBatchDTO().getAddBatchList();
            if (CollectionsUtil.isNotEmpty(addBatchList) && !Objects.equals(isImport, BasicConstant.ONE)) {
                // 非导入时判断数据量限制
                Integer oneStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.ONE_FORM_DATA_NUM, addBatchList.size(), XbbRefTypeEnum.PAYMENT,
                        null);
                Integer allStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, addBatchList.size());
                if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
                }

                if (!Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode())) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
                }
            }

            for (AddMuchFieldPojo addMuchFieldPojo : addBatchList) {
                addMuchFieldPojo.getData().put(PaymentEnum.CONTRACT.getAttr(), contractId.toString());
                addMuchFieldPojo.getData().put(PaymentEnum.CONTRACT_LINK_TEXT.getAttr(), data.getString(FieldTypeEnum.SERIALNO.getAlias()));
            }

            ContractEntityExt contractEntityExt = contractModel.getByKey(contractId, corpid);

            PaymentDTO paymentDTO = new PaymentDTO();
            paymentDTO.setIsImport(isImport);
            paymentDTO.setParentNew(true);
            paymentDTO.setLinkContractEntity(contractEntityExt);
            BeanUtil.copyProperties(saasNeedRedundantAttrPojo.getAddBatchDTO(), paymentDTO);
            paymentDTO.setProcessCreatorId(user.getUserId());

            UserEntity userEntity = userModel.getByKey(user.getUserId(), corpid);
            UserVO userVO = new UserVO();
            BeanUtil.copyProperties(userEntity, userVO);
            paymentDTO.setLoginUser(userVO);
            paymentDTO.setLoginUserName(user.getName());
            paymentDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
            paymentService.pay(paymentDTO);

        }
    }

    public void updatePayment(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        Integer isImport = workflowTransferPOJO.getIsImport();
        User user = workflowTransferPOJO.getUser();
        JSONObject data = pojoData.getData();
        Long contractId = pojoData.getId();

        ContractEntityExt contractEntityExt = contractModel.getByKey(contractId, corpid);

        if (Objects.nonNull(saasNeedRedundantAttrPojo)) {
            Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(data, ContractEnum.LINK_CUSTOMER.getAttr(), 0L);
            if (saasNeedRedundantAttrPojo.getAddBatchDTO() != null ) {

                PaymentDTO paymentDTO = new PaymentDTO();
                paymentDTO.setIsImport(isImport);
                paymentDTO.setParentNew(true);
                paymentDTO.setLinkContractEntity(contractEntityExt);
                BeanUtil.copyProperties(saasNeedRedundantAttrPojo.getAddBatchDTO(), paymentDTO);
                paymentDTO.setProcessCreatorId(user.getUserId());

                UserEntity userEntity = userModel.getByKey(user.getUserId(), corpid);
                UserVO userVO = new UserVO();
                BeanUtil.copyProperties(userEntity, userVO);
                paymentDTO.setLoginUser(userVO);
                paymentDTO.setLoginUserName(user.getName());
                paymentDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                paymentService.pay(paymentDTO);

            }


//            Double realPaymentTotalAmount = 0.0D;
            if (saasNeedRedundantAttrPojo.getAddWriteOffPrepaymentBatchDTO() != null) {
                PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
                BeanUtil.copyProperties(saasNeedRedundantAttrPojo.getAddWriteOffPrepaymentBatchDTO(), paymentSheetDTO);
                paymentSheetDTO.setProcessCreatorId(user.getUserId());
                PaymentSheetAmountVO writeOffPrepaymentAmountVO = paymentSheetAddBatch(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF_PREPAYMENT, customerId);
//                realPaymentTotalAmount = writeOffPrepaymentAmountVO.getRealPaymentTotalAmount();
            }
            if (saasNeedRedundantAttrPojo.getAddPaymentSheetBatchDTO() != null) {
                PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
                BeanUtil.copyProperties(saasNeedRedundantAttrPojo.getAddPaymentSheetBatchDTO(), paymentSheetDTO);
                paymentSheetDTO.setProcessCreatorId(user.getUserId());
                PaymentSheetAmountVO writeOffAmountVO = paymentSheetAddBatch(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF, customerId);
//                Double addPaymentAmount = writeOffAmountVO.getRealPaymentTotalAmount();
//                realPaymentTotalAmount = Arith.add(realPaymentTotalAmount, addPaymentAmount);
            }
            /**
             * 处理合同的已回款金额和未收款金额，坏账金额
             * @author chenshan
             * @date 2019-11-30 12:47
             */
//            if ( realPaymentTotalAmount>0.0D ) {
//                // 更新现金毛利
//                updateCashProfit(corpid, realPaymentTotalAmount, contractId, contractEntityExt);
//            }
        }
    }


    /**
     * Description: 保存回款单
     * @param workflowTransferPOJO
	 * @param saasNeedRedundantAttrPojo
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2021/8/17 15:31
     * @since
     */
    public void savePaymentSheet(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        Integer isImport = workflowTransferPOJO.getIsImport();
        JSONObject data = pojoData.getData();
        Long contractId = pojoData.getId();
        User user = workflowTransferPOJO.getUser();

        ContractEntityExt contractEntityExt = contractModel.getByKey(contractId, corpid);

//        Double realPaymentTotalAmount = 0.0D;
        Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(data, ContractEnum.LINK_CUSTOMER.getAttr(),0L);

        List<AddMuchFieldPojo> writeOffPreSheets = new ArrayList<>();
        List<AddMuchFieldPojo> writeOffSheets = new ArrayList<>();

        if (saasNeedRedundantAttrPojo != null && saasNeedRedundantAttrPojo.getAddWriteOffPrepaymentBatchDTO() != null) {
            writeOffPreSheets = saasNeedRedundantAttrPojo.getAddWriteOffPrepaymentBatchDTO().getAddBatchList();
        }

        if (saasNeedRedundantAttrPojo != null && saasNeedRedundantAttrPojo.getAddPaymentSheetBatchDTO() != null) {
            writeOffSheets = saasNeedRedundantAttrPojo.getAddPaymentSheetBatchDTO().getAddBatchList();
        }
        Integer count  = writeOffPreSheets.size() + writeOffSheets.size();
        if (!Objects.equals(isImport, BasicConstant.ONE)) {
            //非导入时判断数据量限制
            Integer oneStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.ONE_FORM_DATA_NUM, count, XbbRefTypeEnum.PAYMENT_SHEET, null);
            Integer allStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, count);
            if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
            }

            if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
            }
        }

        if (saasNeedRedundantAttrPojo != null && saasNeedRedundantAttrPojo.getAddWriteOffPrepaymentBatchDTO() != null) {
            PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
            paymentSheetDTO.setIsImport(isImport);
            paymentSheetDTO.setParentNew(true);
            paymentSheetDTO.setLinkContractEntity(contractEntityExt);
            BeanUtil.copyProperties(saasNeedRedundantAttrPojo.getAddWriteOffPrepaymentBatchDTO(), paymentSheetDTO);
            paymentSheetDTO.setProcessCreatorId(user.getUserId());
            for (AddMuchFieldPojo addMuchFieldPojo : paymentSheetDTO.getAddBatchList()) {
                addMuchFieldPojo.getData().put(PaymentSheetEnum.CONTRACT.getAttr(), Collections.singletonList(contractId.toString()));
                addMuchFieldPojo.getData().put(PaymentSheetEnum.CONTRACT_LINK_TEXT.getAttr(), Collections.singletonList(data.getString(FieldTypeEnum.SERIALNO.getAlias())));
            }
            PaymentSheetAmountVO writeOffPrepaymentAmountVO = paymentSheetAddBatch(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF_PREPAYMENT, customerId);
//            realPaymentTotalAmount = writeOffPrepaymentAmountVO.getRealPaymentTotalAmount();
        }
        if (saasNeedRedundantAttrPojo != null && saasNeedRedundantAttrPojo.getAddPaymentSheetBatchDTO() != null) {
            PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
            paymentSheetDTO.setIsImport(isImport);
            paymentSheetDTO.setParentNew(true);
            paymentSheetDTO.setLinkContractEntity(contractEntityExt);
            BeanUtil.copyProperties(saasNeedRedundantAttrPojo.getAddPaymentSheetBatchDTO(), paymentSheetDTO);
            // TODO 审批过来的数据是最后审批人的userId
            paymentSheetDTO.setProcessCreatorId(user.getUserId());
            for (AddMuchFieldPojo addMuchFieldPojo : paymentSheetDTO.getAddBatchList()) {
                addMuchFieldPojo.getData().put(PaymentSheetEnum.CONTRACT.getAttr(), Collections.singletonList(contractId.toString()));
                addMuchFieldPojo.getData().put(PaymentSheetEnum.CONTRACT_LINK_TEXT.getAttr(), Collections.singletonList(data.getString(FieldTypeEnum.SERIALNO.getAlias())));
            }

            PaymentSheetAmountVO writeOffAmountVO = paymentSheetAddBatch(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF, customerId);
//            Double addPaymentAmount = writeOffAmountVO.getRealPaymentTotalAmount();
//            realPaymentTotalAmount = Arith.add(realPaymentTotalAmount, addPaymentAmount);
        }

        /**
         * 处理合同的已收款金额，未收款金额，坏账金额
         * @author chenshan
         * @date 2019-11-30 12:56
         */
//        if (realPaymentTotalAmount > 0.0D) {
//            // 更新现金毛利
//            updateCashProfit(corpid, realPaymentTotalAmount, contractId, contractEntityExt);
//        }
    }

    private void updateCashProfit(String corpid, Double sheetAmount, Long contractId, ContractEntityExt contractEntityExt) throws XbbException {
        PaasFormDataEntity contract ;
        if (Objects.nonNull(contractEntityExt)) {
            contract =  contractEntityExt;
        } else {
            contract = contractModel.getByKey(contractId, corpid);
        }

        if (Objects.isNull(contract)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        Double finishMoney = getDoubleOrDefaultFromFormData(contract.getData(), ContractEnum.FINISH_AMOUNT.getAttr(), 0D);
        Double oldCashProfit =  finishMoney - getDoubleOrDefaultFromFormData(contract.getData(), ContractEnum.CONTRACT_COST.getAttr(), 0D);
        Double amount = getDoubleOrDefaultFromFormData(contract.getData(), ContractEnum.AMOUNT.getAttr(), 0D);
        Double badAmount = getDoubleOrDefaultFromFormData(contract.getData(), ContractEnum.BAD_AMOUNT.getAttr(), 0D);
        String orderStatus = FastJsonHelper.getStringFromFormData(contract.getData(), ContractEnum.STATUS.getAttr());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(ContractEnum.CASH_PROFIT.getAttr(), oldCashProfit + sheetAmount);
        Double money = Arith.add(finishMoney ,sheetAmount);
        if (Double.compare(money, BasicConstant.ZERO) == BasicConstant.ZERO) {
            jsonObject.put(ContractEnum.CASH_PROFIT_RATE.getAttr(), BasicConstant.ZERO);
        } else {
            jsonObject.put(ContractEnum.CASH_PROFIT_RATE.getAttr(), Arith.round(Arith.div((oldCashProfit + sheetAmount), money), 4));
        }
        Double newFinishMoney = Arith.add(finishMoney,sheetAmount);
        Double newUnFinishMoney = Arith.sub(Arith.sub(amount, Arith.add(finishMoney,sheetAmount)),badAmount);
        jsonObject.put(ContractEnum.FINISH_AMOUNT.getAttr(), newFinishMoney);
        jsonObject.put(ContractEnum.UN_FINISH_AMOUNT.getAttr(), newUnFinishMoney);
//        if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
//            //订货单则还需要处理收款状态
//            String orderPayMentStatus = OrderPayMentStatusEnum.getOrderPayMentStatus(amount, newUnFinishMoney);
//            jsonObject.put(OrderEnum.RECEIVE_PAYMENT_STATUS.getAttr(), orderPayMentStatus);
//            if (Objects.equals(orderStatus, OrderStatusEnum.PENDING_FINANCIAL_REVIEW.getCode())) {
//                jsonObject.put(OrderEnum.STATUS.getAttr(), OrderStatusEnum.DELIVERED.getCode());
//            }
//        }
        if(Double.compare(amount, BasicConstant.ZERO) == BasicConstant.ZERO) {
            jsonObject.put(ContractEnum.PAY_PERCENT.getAttr(), BasicConstant.ZERO);
        } else {
            jsonObject.put(ContractEnum.PAY_PERCENT.getAttr(), Arith.round(Arith.div(newFinishMoney, amount), 4));
        }
        UpdateDataEntity updateData = ExplainUtil.getUpdateData(contractId, jsonObject, corpid);
        contractModel.updateBatch(Collections.singletonList(updateData), corpid);

    }

    /**
     * Description: 回款单批量保存（走新工作流）
     * @param paymentSheetDTO
	 * @param paymentSheetTypeEnum
	 * @param customerId
     * @return com.xbongbong.pro.paymentsheet.pojo.vo.batch.PaymentSheetAmountVO
     * @throws
     * @author 魏荣杰
     * @date 2021/8/17 16:14
     * @since
     */
    private PaymentSheetAmountVO paymentSheetAddBatch(PaymentSheetDTO paymentSheetDTO, PaymentSheetTypeEnum paymentSheetTypeEnum, Long customerId) throws XbbException {

        String corpid = paymentSheetDTO.getCorpid();
        String userId = paymentSheetDTO.getProcessCreatorId();


        PaymentSheetAmountVO paymentSheetAmountVO = new PaymentSheetAmountVO();
        // 批量新增流水号集合
        List<AddMuchFieldPojo> addBatchList = paymentSheetDTO.getAddBatchList();
        // 开启严控模式后生成流水号
        PaasFormExplainEntity formExplainEntity = paasFormExplainModel.getByFormId(paymentSheetDTO.getFormId(), paymentSheetDTO.getCorpid());
        if (Objects.isNull(formExplainEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        Integer distributorMark = formExplainEntity.getDistributorMark();
        paymentSheetDTO.setDistributorMark(distributorMark);

        //获取一下回款单当前处于什么模式
        Long modelType = fundSetModel.getModelType(corpid, XbbRefTypeEnum.CRM);

        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(formExplainEntity.getExplains(), null);
        FieldAttrEntity fieldAttrEntity = explainMap.get(PaymentEnum.PAYMENT_NO.getAttr());
        if (Objects.nonNull(fieldAttrEntity)) {
            FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
            BeanUtil.copyProperties(paymentSheetDTO, formDataAddDTO);
            for (AddMuchFieldPojo addMuchFieldPojo : addBatchList) {
                if (Objects.equals(fieldAttrEntity.getStrictController(), BasicConstant.ONE) &&  StringUtil.isEmpty(addMuchFieldPojo.getSerialNo())) {
                    String serialNo = "";
                    serialNo = serialNoHelp.getSerialNo(serialNo, corpid, formDataAddDTO.getFormId(), fieldAttrEntity);
                    addMuchFieldPojo.setSerialNo(serialNo);
                }
                addMuchFieldPojo.setSysLong10(modelType);
            }
        }

        try {
            String lang = LocaleContextHolder.getLocale().toString();
            // 删除逻辑
            // 批量删除流水号集合
            List<AddMuchFieldPojo> delBatchList = paymentSheetDTO.getDelBatchList();
            if (CollectionsUtil.isNotEmpty(delBatchList)) {
                for (AddMuchFieldPojo addMuchFieldPojo : delBatchList) {
                    FormDataDeleteBatchDTO formDataDeleteBatchDTO = new FormDataDeleteBatchDTO();
                    formDataDeleteBatchDTO.setDataIdList(Collections.singletonList(addMuchFieldPojo.getId()));
                    formDataDeleteBatchDTO.setIsBusinessRule(0);
                    formDataDeleteBatchDTO.setCorpid(corpid);
                    formDataDeleteBatchDTO.setUserId(userId);
                    formDataDeleteBatchDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                    formDataDeleteBatchDTO.setBusinessType(formExplainEntity.getBusinessType());
                    formDataDeleteBatchDTO.setFormId(formExplainEntity.getFormId());
                    formDataDeleteBatchDTO.setAppId(formExplainEntity.getAppId());
                    formDataDeleteBatchDTO.setMenuId(formExplainEntity.getMenuId());
                    formDataDeleteBatchDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    workflowOperatorDataService.delete(formDataDeleteBatchDTO);
                }

            }

            // 插入数据
            Double amount = 0.0D;
            if(CollectionsUtil.isNotEmpty(addBatchList)){
                for (AddMuchFieldPojo addMuchFieldPojo : addBatchList) {
                    JSONObject data = addMuchFieldPojo.getData();
                    Double realPaymentAmount = FundHelp.getSheetAmount4PaymentSheet(data, paymentSheetTypeEnum.getCode());
                    amount = Arith.add(amount, realPaymentAmount);

                    FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
                    //代表是合同进了工作流，那么当合同通过之后，回款单不管进不进工作流其实都不应该走团队权限校验了
                    formDataAddDTO.setFromApproval(true);
                    formDataAddDTO.setAppId(formExplainEntity.getAppId());
                    formDataAddDTO.setFormId(formExplainEntity.getFormId());
                    formDataAddDTO.setMenuId(formExplainEntity.getMenuId());
                    formDataAddDTO.setSerialNo(addMuchFieldPojo.getSerialNo());
                    formDataAddDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    formDataAddDTO.setBusinessType(paymentSheetTypeEnum.getBusinessType());
                    formDataAddDTO.setSubBusinessType(paymentSheetTypeEnum.getBusinessType());
                    formDataAddDTO.setDataList(data);
                    formDataAddDTO.setIsBusinessRule(0);
                    formDataAddDTO.setCorpid(corpid);
                    formDataAddDTO.setUserId(userId);
                    formDataAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                    JSONArray ownerJsonArray = data.getJSONArray(FieldTypeEnum.OWNERID.getAlias());
                    JSONArray coUserJsonArray = data.getJSONArray(FieldTypeEnum.COUSERID.getAlias());
                    if (Objects.nonNull(ownerJsonArray) && ownerJsonArray.size() > BasicConstant.ZERO) {
                        List<ReturnUserAndDepartmentPojo> ownerIds = ownerJsonArray.toJavaList(ReturnUserAndDepartmentPojo.class);
                        formDataAddDTO.setOwnerId(ownerIds);
                    }
                    if (Objects.nonNull(coUserJsonArray) && coUserJsonArray.size() > BasicConstant.ZERO) {
                        List<ReturnUserAndDepartmentPojo> couserIds = coUserJsonArray.toJavaList(ReturnUserAndDepartmentPojo.class);
                        formDataAddDTO.setCoUserId(couserIds);
                    }
                    workflowOperatorDataService.add(formDataAddDTO);
                }
            }
            paymentSheetAmountVO.setRealPaymentTotalAmount(amount);

            // 更新
            List<AddMuchFieldPojo> updateBatchList = paymentSheetDTO.getUpdateBatchList();
            if (CollectionsUtil.isNotEmpty(updateBatchList)) {
                UserEntity userEntity = userModel.getByKeyIngoreDel(userId, corpid);
                UserVO userVO = new UserVO();
                BeanUtil.copyProperties(userEntity, userVO);
                for (AddMuchFieldPojo addMuchFieldPojo : updateBatchList) {
                    FormDataUpdateDTO formDataUpdateDTO = new FormDataUpdateDTO(formExplainEntity.getFormId(), formExplainEntity.getAppId(), formExplainEntity.getMenuId(), addMuchFieldPojo.getId(), addMuchFieldPojo.getData(), SaasMarkEnum.SAAS.getCode(), paymentSheetTypeEnum.getBusinessType(), paymentSheetTypeEnum.getBusinessType(), null, userVO, corpid, null, PlatFormEnum.INTERNAL.getValue());
                    workflowDataService.update(formDataUpdateDTO);
                }
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.help.saas.ContractForPaymentHelp.paymentSheetAddBatch 回款出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return paymentSheetAmountVO;
    }
}
